const electron = require('electron')
const Menu = electron.remote.Menu


class NativeMenu {


    run(context: EditorApiSystem) {

        let template = [
            {
                label: "文件",
                submenu: [
                    {
                        label: "保存",
                        click: () => {
                            context.executeCommand("Save");
                        },
                        accelerator: "CmdOrCtrl+S"   //electron 设置快捷键
                    },
                    {
                        label: "刷新",
                        role: 'reload',
                        accelerator: "CmdOrCtrl+R"
                    }
                ]
            },
            {
                label: '窗口 ',
                role: 'window',
                submenu: [{
                    label: '最小化',
                    accelerator: 'CmdOrCtrl+M',
                    role: 'minimize'
                }, {
                    label: '切换开发者工具',
                    accelerator: (function () {
                        if (process.platform === 'darwin') {
                            return 'Alt+Command+I'
                        } else {
                            return 'Ctrl+Shift+I'
                        }
                    })(),
                    click: function (item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.toggleDevTools()
                        }
                    }
                }, {
                    type: 'separator'
                }]
            }
        ]

        const menu = Menu.buildFromTemplate(template)
        Menu.setApplicationMenu(menu) // 设置菜单部分
    }

}

class HierarchyPanel {

    private tree: InspireTree;
    private context: EditorApiSystem;
    private currentNode: GameObject;
    private addChildButton: HTMLButtonElement;
    private removeButton: HTMLButtonElement;
    private startGameButton: HTMLButtonElement;
    private addPrefabButton: HTMLButtonElement;
    private customContainer = document.getElementById("hierarchyPanel");  
    //将控制按钮都添加到控制面板
    private controlButtonContainer = document.getElementById("controlPanel");

    run(context: EditorApiSystem) {
        this.context = context;
        this.customContainer.style.overflow = "auto"; //要设置长宽才有效
        this.customContainer.style.height = '100%';
        this.customContainer.style.width = '100%';
        this.customContainer.style.color = '#fefefe';
        this.customContainer.style.display = "flex";
        this.customContainer.style.flexDirection = "column";
        this.tree = new InspireTree({
            data: []
        } as any);
        new InspireTreeDOM(this.tree, {
            editable: true,
            dragAndDrop: true,
            target: this.customContainer

        });
        //运行游戏按钮
        {
            this.startGameButton = document.createElement("button");
            this.startGameButton.innerText = "运行游戏";
            this.startGameButton.style.width = "100%";
            this.startGameButton.style.height = "30px";
            this.controlButtonContainer.appendChild(this.startGameButton);
            this.startGameButton.onclick = () => {
                const BrowserWindow = require('electron').remote.BrowserWindow;
                const win = new BrowserWindow({
                    width: GameSize.width,
                    height: GameSize.height
                })
                win.on('close', () => {

                })
                win.loadFile("index.html")      //启动游戏
                win.webContents.openDevTools()  //打开开发者工具
            }
        }
        //添加图片对象按钮
        {   
          
            this.addChildButton = document.createElement("button");
            this.addChildButton.innerText = "添加图片对象";
            this.addChildButton.style.width = "100%";
            this.addChildButton.style.height = "30px";
            this.controlButtonContainer.appendChild(this.addChildButton);
            this.addChildButton.onclick = () => {  
                this.currentNode = core.getselectiedObject();
                const gameObject = new GameObject();
                const newimageRender = new ImageRenderer();
                newimageRender.image = "assets/newImageObj.png";
                gameObject.id = "新建的图片渲染对象" + gameObject.uuid;
                gameObject.addBehaviour(new Transform());
                gameObject.addBehaviour(newimageRender);
                this.currentNode.addChild(gameObject);

                console.log("成功新建图片对象,可直接修改图片路径");
                hierachyPanel.update(getHierarchyData(core.root));
            };
        }
        //添加预制体对象按钮
        {   
          
            this.addPrefabButton = document.createElement("button");
            this.addPrefabButton.innerText = "添加预制体对象";
            this.addPrefabButton.style.width = "100%";
            this.addPrefabButton.style.height = "30px";
            this.controlButtonContainer.appendChild(this.addPrefabButton);
            this.addPrefabButton.onclick = () => {  
                this.currentNode = core.getselectiedObject();
                const gameObject = new GameObject();
                gameObject.id = "新建的预制体对象" + gameObject.uuid;
                gameObject.prefabUrl = "prefab/newprefab.json"
                gameObject.addBehaviour(new Transform());
                this.currentNode.addChild(gameObject);

                console.log("成功新建预制体对象,修改文件路径完成创建");
                hierachyPanel.update(getHierarchyData(core.root));
            };
        }
        //删除对象按钮
        {   
            
            this.removeButton = document.createElement("button");
            this.removeButton.innerText = "删除对象";
            this.removeButton.style.width = "100%";
            this.removeButton.style.height = "30px";
            this.controlButtonContainer.appendChild(this.removeButton);
            this.removeButton.onclick = () => {
                this.currentNode = core.getselectiedObject();
                if (this.currentNode.parent) {
                    this.currentNode.parent.removeChild(this.currentNode);
                    delete core.root.$children[this.currentNode.id]; //将对象从引擎的数据中移除 
                    console.log("成功删除" + this.currentNode.id)
                }
                insepectorPanel.clear();
                hierachyPanel.update(getHierarchyData(core.root));
            };
        }

    }

    update(data: HierarchyNode) {
        function buildTreeData(data: HierarchyNode): NodeConfig & { uuid: number } {
            return { text: data.name, children: data.children.map(buildTreeData), uuid: data.uuid }
        }

        const treeData = buildTreeData(data);

        this.tree.load([treeData])
        this.tree.expandDeep();
        this.tree.on('node.selected', (value) => {
            core.$selectedObject = value.uuid   //先取值再发事件
            this.context.executeCommand('SelectGameObject', value.uuid);

        });
        this.tree.on("node.drop", (event, source, target) => {
            const child = GameObject.getGameObject(source.uuid); //旧父子节点
            const parent = GameObject.getGameObject(target.uuid);  //新父子节点
            if (parent)
            {
                parent.addChild(child);
                child.parent.removeChild(child);
            }
            else 
            {
                console.log("移动节点失败!");
            }
        })
    }
}


class InspectorPanel {

    private context: EditorApiSystem;

    run(context: EditorApiSystem) {
        this.context = context;
    }

    update(data: InspectorData) {

        this.clear();
        const gui = new dat.GUI({ autoPlace: false });
        //添加对象名称
        {
            const name = gui.add({ name: data.name }, "name");
            name.onFinishChange((value) => {
                GameObject.getGameObject(data.uuid).id = value;
                hierachyPanel.update(getHierarchyData(core.root));
            });
        }
        
        //是否激活显示
        {
            const isActive = gui.add({ isActive: data.isActive }, "isActive");
            isActive.onFinishChange((value) => {
                GameObject.getGameObject(data.uuid).setActive (value);
                hierachyPanel.update(getHierarchyData(core.root));
            });
        }

        const folder = gui.addFolder(data.name);
        folder.open();
        for (const behaviour of data.behaviours) {
            const behaviourFolder = folder.addFolder(behaviour.name);
            behaviourFolder.open();

            const obj: any = {};
            for (const property of behaviour.properties) {
                obj[property.key] = property.value;
                const controller = behaviourFolder.add(obj, property.key);
                controller.onChange((value) => {
                    // Fires when a controller loses focus.
                    this.context.executeCommand("ModifyBehaviourProperty", {
                        uuid: behaviour.uuid,
                        key: property.key,
                        newValue: value
                    })
                })
            }
        }
          //添加对象的Url
          if ( data.prefabUrl)
          {
            const url= gui.add({ prefabUrl: data.prefabUrl }, "prefabUrl");
            url.onFinishChange((value) => {
                GameObject.getGameObject(data.uuid).prefabUrl = value;
                hierachyPanel.update(getHierarchyData(core.root));
                
            });
        }

        const controller1 = gui.add({
            AddComponent: ""
        }, "AddComponent", core.getAllBehaviourClassName());
        controller1.onChange((value) => {
            this.context.executeCommand("AddBehaviourOnGameObject", {
                uuid: data.uuid,
                behaviourName: value,
            })
        })


        const controller2 = gui.add({
            RemoveComponent: ""
        }, "RemoveComponent", core.getAllBehaviourClassName());
        controller2.onChange((value) => {
            this.context.executeCommand("RemoveBehaviourOnGameObject", {
                uuid: data.uuid,
                behaviourName: value,
            })
        })

        const customContainer = document.getElementById('inspectorPanel');
        customContainer.appendChild(gui.domElement);
    }

    clear() {
        const customContainer = document.getElementById('inspectorPanel');
        for (const child of customContainer.children) {
            child.remove()
        }
    }
}

class ResourcePanel {

    private context: EditorApiSystem;

    run(context: EditorApiSystem) {
        this.context = context;

        const div = document.getElementById("resourcePanel");

        //设置资源布局为横向灵活排列
        div.style.overflow = "auto";
        div.style.width = "100%";
        div.style.height = "100%";
        div.style.display = "flex";
        div.style.textAlign = "center";
        div.style.flexWrap = "wrap"
        const scenes = core.configData.scenes;
        for (let scene of scenes) {
            const icon = new FileIcon();
            icon.create(scene);
            const view = icon.getView()
            view.style.marginLeft = "20px";
            div.appendChild(view);
            view.onclick = () => {
                context.executeCommand("ChangeScene", scene)
                console.log('切换场景')
            }
        }

        div.onclick = () => {

        }
    }
}


class FileIcon {

    private view = document.createElement("div");
    create(labelName: string) {
        const img = document.createElement("img");
        img.src = './editor/ui/file-icon.png';
        img.style.width = '64px'
        const label = document.createElement('p');
        label.innerText = labelName;
        label.style.color = 'white';
        this.view.appendChild(img);
        this.view.appendChild(label);
    }

    getView() {
        return this.view;
    }
}


const nativeMenu = new NativeMenu();
const hierachyPanel = new HierarchyPanel();
const insepectorPanel = new InspectorPanel()
const resourcePanel = new ResourcePanel();